﻿using AutoMapper;
using B.S.DataBase.Domain;
using B.S.DataBase.ErrorCode;
using B.S.DataBase.Infrastructure;
using B.S.DataBase.Write.API.Application.Commands;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace B.S.DataBase.Write.API.Application.Handlers
{
    /// <summary>
    /// 商品基本信息新增命令处理
    /// </summary>
    public class CreateProductHandler : IRequestHandler<CreateProductCommand, APIResult<int>>
    {
        private readonly IBaseRepository<Product> ProductRepository;
        private readonly IMapper mapper;

        public CreateProductHandler(IBaseRepository<Product> productRepository, IMapper mapper)
        {
            ProductRepository = productRepository;
            this.mapper = mapper;
        }

        public async Task<APIResult<int>> Handle(CreateProductCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();

            var entity = mapper.Map<Product>(request);

            entity.BatchId = Guid.NewGuid().ToString();
            entity.CreationDate = DateTime.Now;


            var list = ProductRepository.GetAllAsync().Where(x => x.BatchId == request.BatchId).Count();
            if (list > 0)
            {
                result.Code = APIEnums.Fail;
                result.Meg = "商品名称重复";
                return await Task.FromResult(result);
            }
            else
            {
                var dto = ProductRepository.AddAsync(entity).Result;
                if (dto > 0)
                {
                    result.Code = APIEnums.Success;
                    result.Meg = "新增成功";
                    result.Data = dto;
                }
                else
                {
                    result.Code = APIEnums.Fail;
                    result.Meg = "新增失败";
                    return await Task.FromResult(result);
                }
            }

            return await Task.FromResult(result);
        }
    }
}
